using UniversalAdminSystem.Domian.PermissionManagement.Services;
using UniversalAdminSystem.Domian.PermissionManagement.ValueObjects;

namespace UniversalAdminSystem.Infrastructure.Services;

/// <summary>
/// 权限规则配置服务
/// 职责：统一管理权限规则配置的加载、更新、热重载
/// </summary>
public class PermissionRuleConfigService : IDisposable
{
    private readonly PermissionRuleFileService _fileService;
    private readonly string _configFilePath;

    public PermissionRuleConfigService(string configFilePath)
    {
        _configFilePath = configFilePath;
        _fileService = new PermissionRuleFileService(configFilePath, OnConfigChanged);
    }

    /// <summary>
    /// 初始化配置（应用启动时调用）
    /// </summary>
    public void Initialize()
    {
        try
        {
            if (File.Exists(_configFilePath))
            {
                var rules = _fileService.LoadFromFile();
                ResourceActionValidator.LoadRules(rules);
                Console.WriteLine("权限规则配置加载成功");
                
                // 启动文件监听
                _fileService.StartFileWatcher();
            }
            else
            {
                Console.WriteLine("权限规则配置文件不存在，使用默认配置");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"权限规则配置初始化失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取当前配置
    /// </summary>
    public Dictionary<PermissionAction, HashSet<string>> GetCurrentConfig()
    {
        return ResourceActionValidator.GetCurrentRules();
    }

    /// <summary>
    /// 更新配置（支持后台维护）
    /// </summary>
    public void UpdateConfig(Dictionary<string, List<string>> newConfig)
    {
        try
        {
            // 转换为领域模型格式
            var rules = newConfig.ToDictionary(
                kv => Enum.Parse<PermissionAction>(kv.Key, true),
                kv => kv.Value.ToHashSet()
            );

            // 更新校验器
            ResourceActionValidator.LoadRules(rules);
            
            // 保存到文件
            _fileService.SaveToFile(rules);
            
            Console.WriteLine("权限规则配置更新成功");
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"更新权限规则配置失败: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 手动刷新配置
    /// </summary>
    public void RefreshConfig()
    {
        try
        {
            var rules = _fileService.LoadFromFile();
            ResourceActionValidator.LoadRules(rules);
            Console.WriteLine("权限规则配置刷新成功");
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"刷新权限规则配置失败: {ex.Message}", ex);
        }
    }

    /// <summary>
    /// 配置变更回调
    /// </summary>
    private void OnConfigChanged(Dictionary<PermissionAction, HashSet<string>> rules)
    {
        ResourceActionValidator.LoadRules(rules);
    }

    public void Dispose()
    {
        _fileService?.Dispose();
    }
} 